package cn.bnjy.service.impl;

import cn.bnjy.common.MessageTypeConstant;
import cn.bnjy.common.WeiXinAccessToken;
import cn.bnjy.common.WeiXinApi;
import cn.bnjy.common.WeiXinConstant;
import cn.bnjy.service.IAsyncService;
import cn.bnjy.util.HttpUtils;
import cn.bnjy.util.ImgUtils;
import cn.bnjy.util.ShellCmdUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 描述：异步发送消息
 *
 * @since: 2018/11/21 22:59
 * @author: chavin
 */
@Service
@Slf4j
@Async
public class AsyncServiceImpl implements IAsyncService {

    @Override
    public void sendMsg(String params) {
        try {
            HttpUtils.post(WeiXinApi.KF_SENDMSG.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()), params);
        } catch (Exception e) {
            log.error("发送信息失败：", e);
        }
    }

    @Override
    public void sendQrcode(String openId, String nickName) {
        try {
            // 调用接口创建临时二维码
            Map<String, Object> qrcodeMap = Maps.newHashMap();
            qrcodeMap.put("expire_seconds", 684000);
            qrcodeMap.put("action_name", "QR_STR_SCENE");
            Map<String, Map<String, String>> actionMap = Maps.newHashMap();
            Map<String, String> sceneMap = Maps.newHashMap();
            sceneMap.put("scene_str", WeiXinConstant.QR_CODE_PREFIX + openId);
            actionMap.put("scene", sceneMap);
            qrcodeMap.put("action_info", actionMap);
            String result = HttpUtils.post(WeiXinApi.GET_TEMP_QRCODE_TICKET.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()), qrcodeMap);
            JSONObject obj = JSON.parseObject(result);
            if(obj.containsKey("errcode")) {
                log.error("创建临时二维码失败");
                return;
            }
            String ticket = URLEncoder.encode(obj.getString("ticket"), WeiXinConstant.UTF8);
            String file = HttpUtils.savePicFromUrl(WeiXinApi.CREATE_TEMP_QRCODE.replace(WeiXinConstant.TICKET, ticket), null, null);
            // 将二维码图片合成海报
            file = createPoster(file, nickName);
            if(StringUtils.isBlank(file)) {
                log.error("合成海报失败，不发送海报给用户");
                return;
            }
            // 通过curl命令将文件上传至临时素材中
            String resultJson = ShellCmdUtils.run(WeiXinApi.CURL_CREATE_TEMP_SOURCE.replace(WeiXinConstant.ACCESS_TOKEN, WeiXinAccessToken.getToken()).replace("IMGPATH", file).replace("TYPE", "image"));
            String mediaId = null;
            if(StringUtils.isNotBlank(resultJson)) {
                JSONObject jsonObject = JSON.parseObject(resultJson);
                if(jsonObject.containsKey("errcode")) {
                    log.error("上传至临时素材失败");
                    return;
                }
                mediaId = jsonObject.getString(WeiXinConstant.MEDIA_ID);
            }
            Map<String, String> data = Maps.newHashMap();
            data.put(WeiXinConstant.MEDIA_ID, mediaId);
            sendMore(openId, MessageTypeConstant.IMAGE, data);
        } catch (UnsupportedEncodingException e) {
            log.error("给用户发送二维码失败", e);
        }
    }

    // 生成海报
    private String createPoster(String file, String nickName){
        if(StringUtils.isBlank(file)) {
            return null;
        }
        // 要插入主图片的图片
        List<Map<String, String>> targetImgMapList = Lists.newArrayList();
        Map<String, String> targetImgMap = Maps.newHashMap();
        targetImgMap.put("img", file);
//        targetImgMap.put("x", "630");
//        targetImgMap.put("y", "1708");
//        targetImgMap.put("width", "612");
//        targetImgMap.put("height", "612");
        targetImgMap.put("x", "169");
        targetImgMap.put("y", "415");
        targetImgMap.put("width", "143");
        targetImgMap.put("height", "143");
        targetImgMapList.add(targetImgMap);
       /* List<Map<String, String>> targetTextMapList = Lists.newArrayList();
        Map<String, String> targetTextMap = Maps.newHashMap();
        String name = "";
        try {
            name = new String(nickName.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("微信名称转UTF-8失败：", e);
        }
        targetTextMap.put("text", nickName.substring(0, name.length() > 6 ? 6 : name.length()));
        targetTextMap.put("x", "120");
        targetTextMap.put("y", "400");
        targetTextMapList.add(targetTextMap);*/
        String sourceImg = "/home/wx/static/images/qrcode/qrcode-template.jpg";
        String posterfile = ImgUtils.compound(sourceImg, targetImgMapList, null);
        return posterfile;
    }

    @Override
    public void sendMore(String openId, String type, Object data) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("touser", openId);
        map.put("msgtype", type);
        map.put(type, data);
        sendMsg(JSON.toJSONString(map));
    }

}
